package com.xry.test1.Util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xry.test1.dao.UserRepository;
import com.xry.test1.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Optional;


@Slf4j
@Component
public class JWTUtil {
    private static final String SECRET_KEY = "secret";
    /**
     * 过期时间
     */
    private static final long EXPIRE_TIME = 1000 * 60 * 60 * 2;

    private static UserRepository userRepository;
    @Autowired
    public void setUserRepository(UserRepository userRepository) {
        JWTUtil.userRepository = userRepository;
    }



    /**
     * 使用用户名签发token，密码作为私钥
     * @param username 用户名
     * @return token
     */
//    用户名 密码 角色创造token对象
    public static String createToken(String username) {
        String token = com.auth0.jwt.JWT.create()
                .withClaim("username", username)
                .withClaim("userId", getUserIdByUsername(username))
                .withNotBefore(new Date(System.currentTimeMillis()))
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                .sign(Algorithm.HMAC512(SECRET_KEY));
        log.info("token: " + token);
        return token;
    }

    private static Long getUserIdByUsername(String username) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 返回该用户的 ID
        return user.getId();
    }

    /**验证token
     * @param token
     * @return
     */
    public static DecodedJWT verifyToken(String token) {
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC512(SECRET_KEY)) // 替换为你的密钥
                .build()
                .verify(token);

        // 获取 token 中的用户名
        String username = decodedJWT.getClaim("username").asString();

        // 查询数据库中是否存在该用户名
        Optional<User> userOpt = userRepository.findByUsername(username);
        if (userOpt.isEmpty()) {
            throw new RuntimeException("用户不存在或已被删除");
        }

        return decodedJWT;
    }
}
